package com.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.Result.BaseRespones;
import com.Result.StatusCode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class UserOperation {
	
	/**
	 * @apiDefine User 登录
	 */

	/**
	 * @apiDefine loginErrorMsg 登录失败响应信息
	 * @apiError 110 未知错误
	 * @apiError 2004 用户名或密码错误
	 * @apiError 2005 用户类别错误
	 */

	/**
	 * @apiDefine loginSuccessMsg 登录成功响应信息
	 * @apiSuccess {int} code 响应码
	 * @apiSuccess {String} msg 响应信息
	 * @apiSuccess {timestamp} timestamp 时间戳
	 * @apiSuccess {Object} res 用户信息
	 */

	/**
	 * @api{Post} /Login?method=Login 登录
	 * @apiName Login
	 * @apiGroup User
	 * @apiDescription 用户登录
	 * @apiVersion 0.0.1
	 * 
	 * @apiParamExample {json} 学生登录请求样例 
	 * { 
	 * "loginName":"laolingjie",
	 * "password":"laolingjie", 
	 * "userIdentity":1 
	 * }
	 * 
	 * @apiParamExample {json} 管理员登录请求样例 
	 * {
     *	"loginName": "huanglingfeng",
     *	"password": "huanglingfeng",
     *	"userIdentity": 2
	 * }
	 * 
	 * @apiUse loginSuccessMsg
	 * @apiUse loginErrorMsg
	 * 
	 * @apiSuccessExample {json} 学生登录成功 
	 * {
	 * 'code':2001,
	 * 'msg':'学生用户登录成功',
	 * 'timestamp':'2019-06-08 20:57:26',
	 * 'data':
	 * 	{
	 * 	 'StuID':10001,
	 * 	 'UserID':10001,
	 * 	 'StuPhone':'110',
	 * 	 'StuMoney':666
	 *  }
	 * }
	 * 
	 * @apiSuccessExample {json} 管理员登录成功 
	 * {
	 * 'code':2006,
	 * 'msg':'管理员用户登录成功',
	 * 'timestamp':'2019-06-11 11:18:14',
	 * 'data':
	 *   { 
	 *   'AdminID':1,
	 *   'UserID':10009,
	 *   'AdminName':'shuaige'
	 *   }
	 * }
	 * 
	 * 
	 * @apiErrorExample {json} Error-Response: 
	 * { 
	 * "code":2004, 
	 * "msg":"用户名或密码错误",
	 * "timestamp":"May 19, 2019, 6:26:44 PM"
	 * }
	 * 
	 */
	public String userLogin(String requestString) throws IOException{
		String resource = "mybatisConfig.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		// 返回对象声明
		BaseRespones response = null;
		// 用户mapper
		UserMapper mapper = (UserMapper) session.getMapper(UserMapper.class);
		System.out.println(requestString);
			
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();  
				
		User user=null;
		try {
			user = gson.fromJson(requestString, User.class);
		} catch (Exception e) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		if (user==null){
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		// 反序列化错误
		if (user == null) {
			response = new BaseRespones(StatusCode.unknown);
			return gson.toJson(response);
		}
		// 身份标识错误
		if (!(user.getUserIdentity() == 1 || user.getUserIdentity() == 2 || user.getUserIdentity() == 3)) {
			response = new BaseRespones(StatusCode.userIdentityError);
			return gson.toJson(response);
		}

		User resUser = null;
		if (user != null && user.getClass() != null && user.getLoginName() != null && user.getPassword() != null) {
			Map paramMap = new HashMap();
			paramMap.put("loginName", user.getLoginName());
			paramMap.put("password", user.getPassword());
			paramMap.put("userIdentity", user.getUserIdentity());
			resUser = mapper.getUser(paramMap);
		}
		// 未匹配记录 登录失败
		if (resUser == null) {
			response = new BaseRespones(StatusCode.loginFail);
			return gson.toJson(response);
		}
		// 获取用户信息
		switch (resUser.getUserIdentity()) {
		// 学生
		case 1:
			StudentOperation studentOperation = new StudentOperation();
			Student student = StudentOperation.getStudentbyID(resUser.getUserID());
			if(student==null)
				response = new BaseRespones(StatusCode.loginFail);
			else
				response = new BaseRespones(StatusCode.studentLoginSuccess);
			response.setData(student);
			return gson.toJson(response);
		case 2:
			AdminOperation adminOperation = new AdminOperation();
			Admin admin = adminOperation.getAdminbyID(resUser.getUserID());
			if(admin==null)
				response = new BaseRespones(StatusCode.loginFail);
			else
				response = new BaseRespones(StatusCode.AdminLoginSuccess);
			response.setData(admin);
			return gson.toJson(response);
		default:
			response = new BaseRespones(StatusCode.unknown);
			return gson.toJson(response);
		}

	}
	/**
	 * @apiDefine RegisterErrorMsg 注册失败响应信息
	 * @apiError 110 未知错误
	 * @apiError 111 反序列化错误
	 * @apiError 112 序列化错误
	 * @apiError 1002 该用户民已经存在
	 * @apiError 1003 注册信息不完整
	 * @apiError 1004 密码过于简单
	 */

	/**
	 * @apiDefine RegisterSuccessMsg 注册成功响应信息
	 * @apiSuccess {int} code 响应码
	 * @apiSuccess {String} msg 响应信息
	 * @apiSuccess {timestamp} timestamp 时间戳
	 */

	/**
	 * @api{Insert} /Login?method=Register 用户注册
	 * @apiDescription
	 * @apiName Register
	 * @apiGroup User
	 * @apiDescription
	 * @apiVersion 0.0.1
	 * 
	 * @apiUse RegisterErrorMsg
	 * @apiUse RegisterSuccessMsg
	 * 
	 * 
	 * @apiParamExample {json} 学生注册请求样例 
	 * {
	 *    "loginName": "mingmingming",
	 *    "password": "nihaoma",
	 *    "userIdentity": 1,
	 *    "StuPhone":"123124"
	 * }
	 * 
	 * @apiParamExample {json} 管理员注册请求样例 
	 * {
	 *    "loginName": "mingmingming",
	 *    "password": "nihaoma",
	 *    "userIdentity": 2,
	 *     "AdminName":"12345"
	 * }
	 * @apiSuccessExample {json} 
	 * Success-Response: 
	 * { 
	 * "code":1001, 
	 * "msg":"注册成功",
	 * "timestamp":"May 19, 2019, 8:50:20 PM" 
	 * }
	 */
	public String userRegist(String requestString) throws IOException{
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		// 返回对象声明
		BaseRespones response = null;
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();  
		User user=null;
		try {
			user = gson.fromJson(requestString, User.class);
		} catch (Exception e) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		if (user==null){
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}
		
		// 用户mapper
		UserMapper mapper = (UserMapper) session.getMapper(UserMapper.class);

		// 检查是否有相同的用户名
		Map paramMap = new HashMap();
		System.out.println(user.getLoginName());
		paramMap.put("loginName", user.getLoginName());
		
		if (mapper.getUser(paramMap) != null) {
			response = new BaseRespones(StatusCode.loginNameUsed);
			return gson.toJson(response);
		}

		// 登录表执行插入
		int userID = mapper.insertUser(user);
		if (userID <= 0) {
			response = new BaseRespones(StatusCode.userInsertFail);
			return gson.toJson(response);
		} else {
			session.commit();
			session.close();
		}

		// 用户表执行插入
		int rs = 0;
		Student student=null;
		Admin admin=null;
		switch (user.getUserIdentity()) {
		// 学生
		case 1:
			try {
				student = gson.fromJson(requestString, Student.class);
			}
			catch (Exception e) {
				response = new BaseRespones(StatusCode.jsonDeserializeFail);
				return gson.toJson(response);
			}
			System.out.println(user.getUserID());
			student.setUserID(user.getUserID());
			//
			student.setStuMoney(0);
			
			JsonObject jo= (JsonObject) new JsonParser().parse(requestString).getAsJsonObject();
			String  phone=jo.get("StuPhone").getAsString();
			student.setStuPhone(phone);
			StudentOperation studentOperation = new StudentOperation();
			rs = studentOperation.insertStudent(student);
			if (rs == 0) {
				response = new BaseRespones(StatusCode.studentInsertFail);
				return gson.toJson(response);
			}
			break;
		case 2:
			try {
				admin = gson.fromJson(requestString, Admin.class);
			}
			catch (Exception e) {
				response = new BaseRespones(StatusCode.jsonDeserializeFail);
				return gson.toJson(response);
			}
			System.out.println(user.getUserID());
			admin.setUserID(user.getUserID());
			JsonObject jo1= (JsonObject) new JsonParser().parse(requestString).getAsJsonObject();
			String adminName=jo1.get("AdminName").getAsString();
			admin.setAdminName(adminName);
			AdminOperation adminOperation = new AdminOperation();
			rs = adminOperation.insertAdmin(admin);
			if (rs == 0) {
				response = new BaseRespones(StatusCode.adminInsertFail);
				return gson.toJson(response);
			}
			
			break;
		default:
			break;
		}

		System.out.println(gson.toJson(user));

		response = new BaseRespones(StatusCode.registSuccess);
		return gson.toJson(response);
	}
	/**
	 * @apiDefine updatePasswdErrorMsg 更新密码失败响应信息
	 * @apiError 110 未知错误
	 * @apiError 111 反序列化错误
	 * @apiError 112 序列化错误
	 * @apiError 1031 原密码错误
	 * @apiError 1031 更新密码错误
	 *
	 */

	/**
	 * @apiDefine updatePasswdSuccessMsg 登录成功响应信息
	 * @apiSuccess {int} code 响应码
	 * @apiSuccess {String} msg 响应信息
	 * @apiSuccess {timestamp} timestamp 时间戳
	 */

	/**
	 * @api{Insert} /Login?method=updatePassword 用户修改密码
	 * @apiDescription
	 * @apiName updatePasswd
	 * @apiGroup User
	 * @apiDescription
	 * @apiVersion 0.0.1
	 * 
	 * @apiUse updatePasswdErrorMsg
	 * @apiUse updatePasswdSuccessMsg
	 * 
	 * 
	 * @apiParamExample {json} 更改密码请求样例
	 * {
	 *"userID":10007
	 *"password":"nihaoma",
	 *"newpassword":"fffqqq"
     *}
	 * 
	 * 
	 * @apiSuccessExample {json} 
	 * Success-Response: 
	 * { 
	 * "code":1031, 
	 * "msg":"更新密码成功",
	 * "timestamp":"May 19, 2019, 8:50:20 PM" 
	 * }
	 * 
	 * @apiErrorExample {json}
	 * Error-Response: 
	 * { 
	 * "code":1031, 
	 * "msg":"原密码错误",
	 * "timestamp":"May 19, 2019, 6:26:44 PM"
	 * }
	 */
	
	public String userUpdatePasswd(String requestString) throws IOException{
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();

		// 返回对象声明
		BaseRespones response = null;

		requestString = "{'userID':10001,'password':'qaz123456','newPassword':'123456'}";

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();  
		User user=null;
		try {
			user = gson.fromJson(requestString, User.class);
		} catch (Exception e) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		if (user==null){
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		// 用户mapper
		UserMapper mapper = (UserMapper) session.getMapper(UserMapper.class);

		// 校验原密码
		Map paramMap = new HashMap();
		System.out.println(user.getUserID());
		paramMap.put("userID", user.getUserID());
		paramMap.put("password", user.getPassword());
		if (mapper.getUser(paramMap) != null) {
			response = new BaseRespones(StatusCode.updatePasswordFailOldNotMatch);
			return gson.toJson(response);
		}
		
		// 更新密码
		JsonObject jo= (JsonObject) new JsonParser().parse(requestString).getAsJsonObject();
		String  newpasswd=jo.get("newPassword").getAsString();
		
		// 执行更新
		user.setPassword(newpasswd);
		int rs=mapper.updatePassword(user);
		// 更新失败
		if (rs==0) {
			response = new BaseRespones(StatusCode.updatePasswordFail);
			return gson.toJson(response);
		}
		// 更新成功
		session.commit();
		session.close();
		response = new BaseRespones(StatusCode.updatePasswordSuccess);
		return gson.toJson(response);	
		
	}
	/**
	 * @apiDefine updateLoginNameErrorMsg 更新登录名失败响应信息
	 * @apiError 110 未知错误
	 * @apiError 111 反序列化错误
	 * @apiError 112 序列化错误
	 * @apiError 1002 用户名已存在
	 * @apiError 1041 更新登录名失败
	 * @apiError 1042 输入的密码错误
	 *
	 */

	/**
	 * @apiDefine updateLoginNameSuccessMsg 更新登录名成功响应信息
	 * @apiSuccess {int} code 响应码
	 * @apiSuccess {String} msg 响应信息
	 * @apiSuccess {timestamp} timestamp 时间戳
	 */

	/**
	 * @api{Insert} /Login?method=updateLoginName 用户修改登录名
	 * @apiDescription
	 * @apiName updateLoginName
	 * @apiGroup User
	 * @apiDescription
	 * @apiVersion 0.0.1
	 * 
	 * @apiUse updateLoginNameErrorMsg
	 * @apiUse updateLoginNameSuccessMsg
	 * 
	 * 
	 * @apiParamExample {json} 更改登录名请求样例
	 * {
	 * "userID":10007,
	 * "loginName":"mingmingming" 
	 * "password":"nihaoma",
	 * "newLoginName":"123456"
	 * }
	 * 
	 * 
	 * @apiSuccessExample {json} 
	 * Success-Response: 
	 * { 
	 * "code":1040, 
	 * "msg":"更新用户名成功",
	 * "timestamp":"May 19, 2019, 8:50:20 PM" 
	 * }
	 * 
	 * @apiErrorExample {json}
	 * Error-Response: 
	 * { 
	 * "code":1002, 
	 * "msg":"用户名已经存在",
	 * "timestamp":"May 19, 2019, 6:26:44 PM"
	 * }
	 */
	public String userUpdateLoginName(String requestString) throws IOException{
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		
		// 返回对象声明
		BaseRespones response = null;

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();  
		User user=null;
		try {
			user = gson.fromJson(requestString, User.class);
		} catch (Exception e) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}

		if (user==null){
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}
		
		UserMapper mapper=(UserMapper)session.getMapper(UserMapper.class);
		
		// 检查要更新的用户名是否存在
		JsonObject jo= (JsonObject) new JsonParser().parse(requestString).getAsJsonObject();
		String  newLoginName=jo.get("newLoginName").getAsString();
		// 检查是否有相同的用户名
		Map paramMap = new HashMap();
		paramMap.put("loginName", newLoginName);
		System.out.println(newLoginName);
		if (mapper.getUser(paramMap) != null) {
			response = new BaseRespones(StatusCode.loginNameUsed);
			return gson.toJson(response);
		}
		user.setLoginName(newLoginName);
		// 执行更新  
		int rs=mapper.updateLoginName(user);
		// 更新失败
		if (rs==0) {
			response = new BaseRespones(StatusCode.updateLoginNameFail);
			return gson.toJson(response);
		}
		// 更新成功
		session.commit();
		session.close();
		response = new BaseRespones(StatusCode.updateLoginNameSuccess);
		return gson.toJson(response);	
	}

}
